<template>
  <div class="shop_info">
    <!-- 对私法人账户-->
    <van-form @submit="onSubmit" error-message-align="right" input-align="right">
      <div class="enterise_info_title"><span>*</span>结算卡信息</div>
      <van-field name="front_url" label="" label-width="0.01rem" style="padding-bottom: 0.6rem;"
        :rules="[{ required: true, message: '不能为空' }]">
        <template #input>
          <van-uploader v-model="front_url" :max-count="1" preview-size="100%" accept="image/jpeg,image/png" :after-read="afterReadFront"
            :before-delete="uploadDleteFront">
            <img src="../../../../images/mine/tianjia.png" alt="" class="tianjia_pic" />
          </van-uploader>
          <div class="tianjia_text">银行卡正面</div>
        </template>
      </van-field>
      <van-field name="back_url" label="" label-width="0.01rem" style="padding-bottom: 0.6rem;"
        :rules="[{ required: true, message: '不能为空' }]">
        <template #input>
          <van-uploader v-model="back_url" :max-count="1" accept="image/jpeg,image/png" preview-size="100%" :after-read="afterReadBack"
            :before-delete="uploadDleteBack">
            <img src="../../../../images/mine/tianjia.png" alt="" class="tianjia_pic" />
          </van-uploader>
          <div class="tianjia_text">银行卡反面</div>
        </template>
      </van-field>
      <van-field name="owner_hold_url" label="" label-width="0.01rem" style="padding-bottom: 0.6rem;"
        :rules="[{ required: true, message: '不能为空' }]">
        <template #input>
          <van-uploader v-model="owner_hold_url" :max-count="1" accept="image/jpeg,image/png" preview-size="100%" :after-read="afterReadOwner"
            :before-delete="uploadDleteOwner">
            <img src="../../../../images/mine/tianjia.png" alt="" class="tianjia_pic" />
          </van-uploader>
          <div class="tianjia_text">手持银行卡</div>
        </template>
      </van-field>
      <!-- <div class="enterise_info_title">营业执照</div> -->
      <van-field v-model="bank_name" name="bank_name" label="开户银行" placeholder="请输入开户银行名称"
        :rules="[{ required: true, message: '请输入开户银行名称' }]"/>
      <van-field v-model="region_name" name="region_name" readonly label="开户地区" is-link placeholder="请选择"
        @click="showPopup = true" :rules="[{ required: true, message: '开户地区不能为空' }]" />
      <div class="search-container">
        <van-field v-model="branch_name" placeholder="请输入支行" @input="debouncedSearch" :loading="isLoading"
          name="branch_name" autocomplete="off" label="开户支行" :rules="[{ required: true, message: '请输入开户支行' }]" />
        <div class="custom-dropdown" v-show="showDropdown">
          <div v-for="item in searchResults" :key="item.value" class="dropdown-item" @click="onSelect(item)">
            {{ item.text }}
          </div>
        </div>
      </div>
      <van-field v-model="account" name="account" label="银行卡号" placeholder="请输入银行卡号"
        :rules="[{ required: true, message: '请输入银行卡号' }]" />
      <van-field v-model="phone" name="phone" label="手机号" placeholder="请输入手机号"
        :rules="[{ required: true, message: '请输入手机号' }]" />
      <div style="margin: 16px;">
        <!-- <van-button round block type="default" @click="backBtn" style="width: 95%;margin: 0.32rem auto;"
        >上一步</van-button> -->
        <van-button round block type="info" native-type="submit" color="linear-gradient( 270deg, #1261E2 0%, #4A89EC 100%)"
          v-if="settle.status == -1 || settle.status == 0 || settle.status == 20 || settle.status == 40">保存</van-button>
      </div>
    </van-form>
    <van-button round block type="info" @click="onDraft" style="width: 90%;margin: 0.32rem auto;"
      v-if="settle.id<=0"
      color="linear-gradient( 270deg, #1261E2 0%, #4A89EC 100%)">暂存草稿</van-button>
    <!-- 省市区 -->
    <van-popup v-model="showPopup" position="bottom">
      <van-cascader v-model="cascaderValue" title="请选择地址" :options="options" @close="showPopup = false"
        @change="onChange" @finish="onFinish" active-color="#1D69E4"/>
    </van-popup>
  </div>
</template>
<script>
import { CATE_LIST, OCR_RECOGNIZE, BANK_BRANCH, CACHE_INFO, CACHE_COMMIT } from "@/api/mine";
import { getOssParams, uploadImage, uploadDelete } from "@/api/upload";
import { REGION_LIST } from "@/api/home";
import { setImageUrl ,getImageUrl} from '@/api/upload'; // Adjust the path accordingly
export default {
  props: ['settle'],
  data() {
    return {
      front_url: [],
      back_url: [],
      owner_hold_url: [],
      selectAreaList: [], // 已选中地区
      showPopup: false,
      cascaderValue: "",
      options: [],
      tabIndex: 0,
      region_code: "",
      region_name: "",
      bank_name: "",
      branch_name: "",
      account: "",
      phone: "",
      searchResults: [],
      isLoading: false,
      showDropdown: false,
      valueArray: []
    };
  },
  created() {
    this.debouncedSearch = this.debounce(this.onSearch, 300);

  },
  mounted() {
    window.scrollTo(0, 0)

    // console.log("法人");
    this.fetchRegions(1, 0);

    this.getInfo()
  },
  watch: {
    branch_name(value) {
      if (value.length === 0) {
        this.searchResults = [];
        this.showDropdown = false;
      }
    },
  },
  methods: {
    async getInfo() {
      let params = {
        type: 'store',
        key: 'accountData',

      }
      if(this.settle.id<=0){
        this.$http.get(CACHE_INFO, { params: params }).then(res => {
          if(res.data.content!=''){
          const data = JSON.parse(res.data.content);

          // 回显数据
          this.front_url = setImageUrl(data.front_url) || [];
          this.back_url = setImageUrl(data.back_url) || [];
          this.owner_hold_url = setImageUrl(data.owner_hold_url) || [];
          this.region_code = data.region_code || '';
          this.region_name = data.region_name || '';
          this.bank_name = data.bank_name || '';
          this.branch_name = data.branch_name || '';
          this.account = data.account || '';
          this.phone = data.phone || '';
          this.valueArray = data.valueArray || [];
          }
      })
      }else{
        this.front_url = this.settle.account_data.front_url == '' ? [] : [{ url: this.settle.account_data.front_url }]
          this.back_url = this.settle.account_data.back_url == '' ? [] : [{ url: this.settle.account_data.back_url }]
          this.owner_hold_url = this.settle.account_data.owner_hold_url == '' ? [] : [{ url: this.settle.account_data.owner_hold_url }]
          this.region_code = this.settle.account_data.region_code;
          this.region_name = this.settle.account_data.region_name;
          if (this.settle.account_data.city_code != 0) {
             this.fetchRegions(this.settle.account_data.province_code, 1);
             this.fetchRegions(this.settle.account_data.city_code, 2);
             this.fetchRegions(this.settle.account_data.county_code, 3);
          }
          this.cascaderValue = this.settle.account_data.region_code;
          this.bank_name = this.settle.account_data.bank_name;
          this.branch_name = this.settle.account_data.branch_name;
          this.account = this.settle.account_data.account;
          this.phone = this.settle.account_data.phone;
          this.valueArray = [
            this.settle.account_data.province_code,
            this.settle.account_data.city_code,
            this.settle.account_data.county_code == 0 ? this.settle.account_data.region_code : this.settle.account_data.county_code
          ];
      }

      // const storedData = localStorage.getItem('accountData');
      //   if (storedData) {

      //   }else{

      //   }

    },
    async onSearch() {
      if (this.branch_name.length > 0) {
        this.isLoading = true;
        try {
          const results = await this.mockRemoteSearch(this.branch_name);
          this.searchResults = results.map((item) => ({
            text: item.name,
            value: item.id,
          }));
          this.showDropdown = this.searchResults.length > 0;
        } catch (error) {
          console.error("搜索出错:", error);
        } finally {
          this.isLoading = false;
        }
      } else {
        this.searchResults = [];
        this.showDropdown = false;
      }
    },
    async mockRemoteSearch(keyword) {
      await new Promise((resolve) => setTimeout(resolve, 300));
      const response = await this.$http.get(BANK_BRANCH, {
        params: { name: keyword, limit: 10 },
      });
      const allItems = response.data; // 获取接口返回的数据

      return allItems.filter((item) => item.name.includes(keyword));
    },
    onSelect(item) {
      this.branch_name = item.text;
      this.showDropdown = false;
    },
    debounce(func, wait) {
      let timeout;
      return function executedFunction(...args) {
        const later = () => {
          clearTimeout(timeout);
          func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
      };
    },
    // 选择器变化时的回调
    onChange(res) {
      this.tabIndex = res.tabIndex;
      if (this.tabIndex === 3) {
        return;
      }
      //   console.log(res, "jj");
      //点击加载下一级回调
      this.getSpaceListAgain(res.selectedOptions, res.value);
    },
    getSpaceListAgain(selectedOptions, value) {
      this.$http
        .get(REGION_LIST, {
          params: {
            code: value,
          },
        })
        .then((res) => {
          let { data } = res;

          if (this.tabIndex == 2 && !data.length) {
            data = [{
              code: 0,
              name: '暂不选择',
              parent_code: value
            }]
          }

          if (data && data.length) {
            this.setOptions(selectedOptions, data);
          }
        });
    },
    setOptions(selectedOptions, data) {
      let _options = this.options;
      selectedOptions.forEach((item, index) => {
        if (index) {
          //不是第一个则取下一级children
          _options = _options.children;
        }
        _options =
          _options[_options.findIndex((_item) => _item.value === item.value)];
      });
      //找到最后一级
      _options.children = data.map((item) => {
        return {
          text: item.name,
          value: item.code,
          children: this.tabIndex == 2 ? null : [],
        };
      });
    },
    // 确定省市区
    onFinish({ selectedOptions }) {
      this.showPopup = false;

      this.selectAreaList = selectedOptions;
      let selectArea = selectedOptions.filter((item) => item.value !== 0);
      this.valueArray = selectArea.map((item) => item.value);
      this.region_code = this.valueArray.slice(-1)[0]
      selectedOptions = selectedOptions.filter((item) => {
        return item.value !== 0;
      });

      this.region_name = selectedOptions.map((option) => option.text).join("/");
    },
    async fetchRegions(parentCode, level) {
      const res = await this.$http.get(REGION_LIST, {
        params: {
          code: parentCode,
        },
      });
      let { data } = res;

      if (level == 3 && !data.length) {
        data = [{
          name: '暂无选择',
          code: 0,
          parent_code: parentCode
        }]
      }

      // 省级
      if (level === 0) {
        data.forEach((item) => {
          this.options.push({
            text: item.name,
            value: item.code,
            children: [],
          });
        });
      } else if (level === 1) {
        // 市级数据
        const province = this.options.find((item) => item.value === parentCode);
        if (province) {
          province.children = data.map((item) => ({
            text: item.name,
            value: item.code,
            children: [],
          }));
        }
      } else if (level === 2) {
        // 区/县级数据
        this.options.forEach((province) => {
          const city = province.children.find(
            (item) => item.value === parentCode
          );
          if (city) {
            city.children = data.map((item) => ({
              text: item.name,
              value: item.code,
              children: [],
            }));
          }
        });
      } else if (level === 3) {
        // 街道数据
        this.options.forEach((province) => {
          province.children.forEach((city) => {
            const county = city.children.find(
              (item) => item.value === parentCode
            );
            if (county) {
              county.children = data.map((item) => ({
                text: item.name,
                value: item.code,
              }));
            }
          });
        });
      }
    },
    // 上传银行卡正面
    async afterReadFront(file) {
      try {
        // 获取OSS上传参数
        if (!this.ossParams || this.ossParams.expire_time < Date.now()) {
          this.ossParams = await getOssParams(this.$http);
        }
        if (!this.ossParams) {
          throw new Error("OSS参数未正确设置");
        }
        // 调用封装的上传函数
        await uploadImage(file, this.ossParams, this.front_url);
        let params = {
          type: "bank_card",
          image_url: this.front_url.map((item) => item.url)[0],
          //   face: true,
        };
        this.$http.post(OCR_RECOGNIZE, params).then((res) => {
          //   console.log(res);
          this.bank_name = res.data.bank_card.bank_name;
          //   this.bank_code=res.data.bank_card.bank_code
          this.account = res.data.bank_card.card_number;
        });
      } catch (error) {
        console.error("处理上传错误:", error);
      }
    },
    // 删除银行卡正面
    uploadDleteFront(file) {
      this.front_url = uploadDelete(file, this.front_url);
      //   this.identity_card = {};
    },
    // 上传银行卡反面
    async afterReadBack(file) {
      try {
        // 获取OSS上传参数
        if (!this.ossParams || this.ossParams.expire_time < Date.now()) {
          this.ossParams = await getOssParams(this.$http);
        }
        if (!this.ossParams) {
          throw new Error("OSS参数未正确设置");
        }
        // 调用封装的上传函数
        await uploadImage(file, this.ossParams, this.back_url);
      } catch (error) {
        console.error("处理上传错误:", error);
      }
    },
    // 删除银行卡反面
    uploadDleteBack(file) {
      this.back_url = uploadDelete(file, this.back_url);
      //   this.identity_card = {};
    },
    // 上传银行卡手持
    async afterReadOwner(file) {
      try {
        // 获取OSS上传参数
        if (!this.ossParams || this.ossParams.expire_time < Date.now()) {
          this.ossParams = await getOssParams(this.$http);
        }
        if (!this.ossParams) {
          throw new Error("OSS参数未正确设置");
        }
        // 调用封装的上传函数
        await uploadImage(file, this.ossParams, this.owner_hold_url);
      } catch (error) {
        console.error("处理上传错误:", error);
      }
    },
    // 删除银行卡手持
    uploadDleteOwner(file) {
      this.owner_hold_url = uploadDelete(file, this.owner_hold_url);
      //   this.identity_card = {};
    },
    onSubmit(values) {
      let params = {
        region_name: this.region_name,
        region_code: this.region_code,
        type: 1
      }
      let accountData = {
        front_url: getImageUrl(this.front_url),
        back_url: getImageUrl(this.back_url),
        owner_hold_url: getImageUrl(this.owner_hold_url),
        region_code: this.region_code,
        region_name: this.region_name,
        bank_name: this.bank_name,
        branch_name: this.branch_name,
        account: this.account,
        phone: this.phone,
        valueArray: this.valueArray,
        type: 1
      };
      let data={
                type:'store',
                key:'accountData',
                content:JSON.stringify(accountData)
            }
            if(this.settle.id<=0){
                this.$http.post(CACHE_COMMIT,data).then(res=>{
                })
            }
      // 保存到 localStorage

      this.$emit("corporate", values, this.valueArray, params);
    },
    onDraft() {
      let accountData = {
        front_url: getImageUrl(this.front_url),
        back_url: getImageUrl(this.back_url),
        owner_hold_url: getImageUrl(this.owner_hold_url),
        region_code: this.region_code,
        region_name: this.region_name,
        bank_name: this.bank_name,
        branch_name: this.branch_name,
        account: this.account,
        phone: this.phone,
        valueArray: this.valueArray,
        type: 1
      };
      let data={
                type:'store',
                key:'accountData',
                content:JSON.stringify(accountData)
            }
            this.$http.post(CACHE_COMMIT,data).then(res=>{
                  this.$toast('暂存成功')
            })
      // 保存到 localStorage

    },
    backBtn() {
      this.$emit("settle", 1)
    }
  },
};
</script>
<style scoped lang="scss">
.shop_info {
  ::v-deep .van-icon {
    color: #c0c0c0 !important;
  }
}

.search-container {
  position: relative;
  z-index: 10;
}

.custom-dropdown {
  position: absolute;
  width: auto;
  max-height: 4rem;
  overflow: auto;
  top: 100%;
  right: 10px;
  font-size: 0.24rem;
  background-color: #fff;
  border: 1px solid #dcdee0;
  border-radius: 5px;
  box-shadow: 0 2px 12px rgba(100, 101, 102, 0.12);
}

.dropdown-item {
  padding: 10px 12px;
  cursor: pointer;
  text-align: center;
  border-bottom: 1px solid #f0f0f0;
}

.dropdown-item:hover::after {
  border-color: transparent transparent red transparent;
  /* 悬停时三角形颜色 */
}

.dropdown-item:hover {
  // color: red;
}

.enterise_info_title {
  font-size: 0.28rem;
  font-weight: bold;
  background: #fff;
  padding: 0.2rem;

  span {
    color: red;
  }
}

.tianjia_pic {
  width: 100%;
}

.tianjia_text {
  width: 100%;
  position: absolute;
  bottom: -20px;
  left: 10%;
  transform: translateX(-50%);
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  font-size: 0.24rem;
  color: #999999;
  // line-height: 17px;
  font-style: normal;
}

.enterise_info_tab {
  background-color: #fff;
  display: flex;
  justify-content: space-between;
  padding: 0.2rem;

  &_btn {
    width: 30%;
    border-radius: 0.15rem;
  }
}

.enterise_info_upload_title {
  font-size: 0.28rem;
  font-weight: bold;
  background: #fff;
  // padding: 0.2rem;
  text-align: center;
}

.shop_upload {
  display: flex;
  justify-content: space-between;
  align-items: center;
  // padding: 0.2rem;

  .shop_upload_text {
    line-height: 0.5rem;

    div:nth-child(1) {
      font-size: 0.3rem;
      font-weight: bold;
    }

    div:nth-child(2) {
      font-size: 0.28rem;
      font-weight: 500;
    }

    div:nth-child(3) {
      font-size: 0.24rem;
      font-weight: 500;
      color: red;
    }
  }
}
</style>
